import { useState, useEffect } from 'react';
import { useModel } from 'umi';
import { Form, message, Input, Button } from 'antd';
import { teacherService } from '@/service';
import { executeActionAfterReq } from '@/util/errorHandle';
import styles from './index.less';

function UserInfoPage() {
  const { teacher } = useModel('useTeacher');
  const [teacherData, setTeacherData] = useState({});
  const [canChange, setCanChange] = useState(false);
  useEffect(() => {
    getAllTeacher();
  }, [teacher]);

  const getAllTeacher = async () => {
    const res = await teacherService.getAllTeacher().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      const reqTeacher = res?.data
      ?.find((item: any) => teacher?.tId == item?.tId);
      setTeacherData({
        ...reqTeacher,
        cIds: reqTeacher?.cIds?.replace(new RegExp(/^,/), ''),
        ecIds: reqTeacher?.ecIds?.replace(new RegExp(/^,/), ''),
      });
    })
  }

  const handleEdit = () => {
    setCanChange(true);
  }
  const handleCancel = () => {
    setCanChange(false);
  }
  const handleSubmit = async (values: any) => {
    if (!canChange) {
      return;
    }
    const res = await teacherService.updateTeacher({
      tId: values?.tId,
      tName: values?.tName,
      password: values?.password,
    }).catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, async () => {
      message.info('修改成功');
      await getAllTeacher();
      setCanChange(false);
    })
  }

  const [form] = Form.useForm();
  form.setFieldsValue(teacherData);
  return (
    <div>
      <Form
        name="basic"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        form={form}
        autoComplete="off"
        onFinish={handleSubmit}
        className={styles.form}
      >
        <Form.Item label="教师号" name="tId">
          <Input disabled />
        </Form.Item>
        <Form.Item label="教师名" name="tName">
          <Input disabled={!canChange} />
        </Form.Item>
        <Form.Item label="登录密码" name="password" hidden={!canChange}>
          <Input disabled={!canChange} />
        </Form.Item>
        <Form.Item label="安排的课程" name="cIds">
          <Input disabled />
        </Form.Item>
        <Form.Item label="安排的实验课程" name="ecIds">
          <Input disabled />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 10 }}>
          <Button type="primary" htmlType="button" onClick={handleEdit} className={styles.but}>
            修改信息
          </Button>
          <Button type="primary" htmlType="submit" className={styles.but}>
            确认修改
          </Button>
          <Button type="primary" htmlType="button" onClick={handleCancel} className={styles.but}>
            取消
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default UserInfoPage;
